from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.dbtool import DBTool
from eim import db
from eim.result.simple_result import SimpleResult
import time

reportbp=Blueprint("reportbp","reportbp",__name__,url_prefix="/report")

@reportbp.route("/appendDBTable",methods=["PUT"])
def appendDBTable():
    """
    添加新的数据库表记录
    """
    # 表格编码变量
    tblcode =''
    dbtool:DBTool
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("提交的参数样式不正确，请正确提交参数")
        pmskeys = pms.keys()
        if (('ename' not in pmskeys) or 
            ('cname' not in pmskeys) or 
            ('comment' not in pmskeys)):
            raise Exception("创建数据表记录所需要的参数不完成，请参照接口文档使用正确的参数")
        else:
            from eim.Services.reportService import ReportService
             # 生成新的表格编码
            dbtool = DBTool(db)
            tblcode = dbtool.getNewCode('dbtables','t','',8)
            rs = ReportService(db)
            id = rs.insertNewTable(tblcode,pms['ename'],pms['cname'],pms['comment'])
            return SimpleResult(status='T',value=id).toDict()
    except Exception as es:
        # 如果出现异常回退表格编码
        if(tblcode!=''):
            dbtool.returnCode('dbtables','',tblcode)
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@reportbp.route("/upgradeDBtable/<int:id>",methods=["POST"])    
def upgradeDBTable(id:int):
    """
    更新指定id的数据表条目

    Args:
        id (int): 待更新数据表的id
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("请正确提供更新参数")
        from eim.Services.reportService import ReportService
        rs = ReportService(db)
        rcnt = rs.upgradeTableByid(id,pms)
        return SimpleResult(status="T",value=rcnt).toDict()
    except Exception as es:
        info =str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()


@reportbp.route("/upgradeDBtable/<int:id>",methods=['DELETE'])
def deleteDBTable(id:int):
    """
    删除指定ID的数据表条目

    Args:
        id (int): 待删除数据表信息的ID
    """
    try:
        from eim.Services.reportService import ReportService
        rs = ReportService(db)
        rs.deleteTableRecord(id)
        return SimpleResult(status='T',value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@reportbp.route("/pageDBTables/<int:pn>/<int:ps>",methods=['GET'])
def pageDBTables(pn:int,ps:int):
    """
    分页获取数据表记录

    Args:
        pn (int): 分页页码
        ps (int): 分页页面尺寸
    """
    try:
        from eim.Services.reportService import ReportService
        from eim.result.page_result import PageResult
        rs = ReportService(db)
        page = PageResult(pn=pn,ps=ps)
        total = rs.getDBTableCount()
        res = rs.pageListTableRecord(pn,ps)
        page.pcnt=total
        page.res=res
        vals = page.toDict()
        return SimpleResult(status="T",value=vals).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()


@reportbp.route("/appendDBFieldRec",methods=["PUT"])
def appendDBFieldRec():
    """
    添加数据表字段记录
    """
    from eim.tools.dbtool import DBTool
    dbTool = DBTool(db)
    fcode=""
    datepart = time.strftime('%Y%m%d',time.localtime())
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("提交的参数类型必须为json类型")
        fcode = dbTool.getNewCode('tablecolumns','col',datepart,6)
        from eim.Services.reportService import ReportService
        rs=ReportService(db)
        newid = rs.insertNewField(fcode,pms['tblcode'],pms['ename'],pms['cname'],pms['ftype'],pms['flength'],pms['comment'])
        return SimpleResult(status='T',value=newid).toDict()
    except Exception as es:
        dbTool.returnCode('tablecolumns',datepart,fcode)
        info =str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@reportbp.route("/getTblCols/<string:tblcode>",methods=["GET"])
def getTableColumns(tblcode:str):
    """
    获取指定数据表格的列

    Args:
        tblcode (str): 数据表编码
    """
    try:
        from eim.Services.reportService import ReportService
        rs = ReportService(db)
        cols = rs.getColsByTblcode(tblcode)
        return SimpleResult(status='T',value=cols).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@reportbp.route("/getColsByTname/<string:tblname>",methods=["GET"])    
def getTableColumnsByTableName(tblname:str):
    """
    获取指定名称的数据表列

    Args:
        tblname (str): 数据表名称
    """
    try:
        from eim.Services.reportService import ReportService
        rs=ReportService(db)
        tblcode = rs.getDBTaleCode(tblname)
        cols = rs.getColsByTblcode(tblcode)
        return SimpleResult(status="T",value=cols).toDict()
    except Exception as es:
        info:str = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    

@reportbp.route("/upgradeTblCol/<int:id>",methods=["POST"])    
def upgradeTblCol(id:int):
    """
    更新指定id的数据表字段信息

    Args:
        id (int): 待更新的数据表字段的id
    """
    try:
        from eim.Services.reportService import ReportService
        rs = ReportService(db)
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("提交的参数格式不正确")
        rc = rs.upgradeTblCol(id,pms)
        return SimpleResult(status="T",value=rc).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()


@reportbp.route("/deleteTblCol/<int:id>",methods=["DELETE"])
def deleteTblCol(id:int):
    """
    删除指定ID的数据表列

    Args:
        id (int): 待删除的数据表列ID
    """
    try:
        from eim.Services.reportService import ReportService
        rs=ReportService(db)
        rs.deleteTblCol(id)
        return SimpleResult(status="T",value=1).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()